package org.sean.common.evaluting;

import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.MapContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 表达式求值的帮助类
 *
 * @author sean
 */
public class NumberEvaluateUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(NumberEvaluateUtils.class);

    private static JexlEngine engine = null;

    /**
     * 获得默认的引擎
     * @return
     */
    public static JexlEngine defaultEngine() {
        if (engine == null) {
            engine = new JexlBuilder().cache(512).strict(true).silent(false).create();
        }
        return engine;
    }

    /**
     * 计算表达式的值
     * @param engine 表达式引擎
     * @param expression 表达式
     * @param contexts 上下文
     * @return 返回计算的值
     */
    public static Number evaluate(JexlEngine engine, String expression, INumberEvaluateContext... contexts) {
        Map<String, Number> contextMap = new HashMap<>();
        if (contexts != null && contexts.length > 0) {
            Stream.of(contexts).forEach(eContext -> {
                Map<String, Number> iContext = eContext.getContextMap();
                if (iContext != null) {
                    contextMap.putAll(iContext);
                }
            });
        }
        return evaluate(engine, expression, contextMap);
    }

    /**
     * 计算表达式的值
     * @param engine
     * @param expression
     * @param contextMap
     * @return
     */
    public static Number evaluate(JexlEngine engine, String expression, Map<String, Number> contextMap) {
        if (expression == null || "".equals(expression.trim())) {
            LOGGER.error("Invalid expression and the value will e set as 0");
            return 0;
        }
        MapContext mapContext = new MapContext();
        if (contextMap != null) {
            contextMap.forEach(mapContext::set);
        }
        if (engine == null) {
            engine = defaultEngine();
        }
        //计算上下文
        Number result = 0;
        JexlExpression exp = parseExpression(engine, expression);
        if (exp != null) {
            result = (Number) exp.evaluate(mapContext);
        }
        return result;
    }

    /**
     * 检查是否为合法的表达式
     * @param engine
     * @param expression
     * @return
     */
    public static boolean isValidExpression(JexlEngine engine, String expression) {
        return parseExpression(engine, expression) != null;
    }

    /**
     * 解析表达式
     * @param engine
     * @param expression
     * @return
     */
    public static JexlExpression parseExpression(JexlEngine engine, String expression) {
        //表达式为空则返回空
        if (expression == null || "".equals(expression.trim())) {
            return null;
        }
        //获得引擎
        if (engine == null) {
            engine = defaultEngine();
        }
        JexlExpression exp = null;
        try {
            exp = engine.createExpression(expression);
        } catch (Exception e) {
            LOGGER.error("Fail to parse the expression {} due to exception found", expression);
            LOGGER.error(e.getMessage(), e);
        }
        return exp;
    }

    /**
     * 将业务表达式转换为表达式代码（表达式可能存在嵌套，所以只能使用parameterAliase中的参数来计算）
     * @param expression
     * @param parameterAliases
     * @param expressions
     * @return
     */
    public static String convertExpressionCodes(BusinessExpression expression, Map<String, String> parameterAliases, List<BusinessExpression> expressions) {
        if (expression == null) {
            return "";
        }
        String exp = expression.getExpression();
        if (exp.contains(expression.getName())) {
            LOGGER.error("The expression cannot have dependency on itself, current expression name is {}, and the exp is {}", expression.getName(), exp);
            return "";
        }
        BusinessExpression target = null;
        try {
            target = convertLoopExpressions(expression, expressions == null ? Collections.emptyList() : expressions.stream().filter(e -> !e.getName().equals(expression.getName())).collect(Collectors.toList()));
        } catch (Exception e) {
            LOGGER.error("Fail to convert the expression, it must be caused by over max iteration times, and the expression is {} with name {}", expression.getExpression(), expression.getName());
            LOGGER.error(e.getMessage(), e);
        }
        if (target == null) {
            return "";
        } else {
            String result = target.getExpression();
            if (parameterAliases != null && parameterAliases.size() > 0) {
                for (Map.Entry<String, String> entry : parameterAliases.entrySet()) {
                    if (result.contains(entry.getValue())) {
                        result = result.replace(entry.getValue(), entry.getKey());
                    }
                }
            }
            return result;
        }
    }

    /**
     * 递归转换表达式为基础变量
     * @param expression
     * @param expressions
     * @return
     */
    public static BusinessExpression convertLoopExpressions(BusinessExpression expression, List<BusinessExpression> expressions) {
        if (expression == null) {
            return null;
        }
        if (expressions == null || expressions.size() < 1) {
            return expression;
        }
        String exp = expression.getExpression();
        //替换
        for (BusinessExpression e : expressions) {
            if (!e.getName().equals(expression.getName())) {
                if (exp.contains(e.getName())) {
                    exp = exp.replace(e.getName(), "(" + e.getExpression() + ")");
                }
            }
        }
        BusinessExpression target = new BusinessExpression(expression.getName(), exp);
        if (expressions.stream().anyMatch(e -> target.getExpression().contains(e.getName()))) {
            return convertLoopExpressions(target, expressions);
        } else {
            return target;
        }
    }
}
